package cn.ubeta.b2c.widget.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import cn.ubeta.b2c.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ruily on 5/24/16.
 */
public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    protected static final int HEADER_VIEW = 0x00000111;
    protected static final int LOADING_VIEW = 0x00000222;
    protected static final int FOOTER_VIEW = 0x00000333;
    protected static final int EMPTY_VIEW = 0x00000555;

    private OnItemChildClickListener mChildClickListener;
    private OnItemClickListener onItemClickListener;
    private OnItemLongClickListener onItemLongClickListener;

    private View mHeaderView;
    private View mFooterView;
    private View mEmptyView;
    private View mLoadingView;

    private List<T> mData;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private int mLayoutResId;

    private boolean mNextLoadEnable;
    private boolean mEmptyEnable;

    private int minNumShowFooterView = 0;

    /**
     * 基类构造函数
     *
     * @param context
     * @param layoutResId //item 布局文件
     * @param data
     */
    public BaseRecyclerAdapter(Context context, int layoutResId, List<T> data) {
        this.mData = data == null ? new ArrayList<T>() : new ArrayList<>(data);
        this.mContext = context;
        this.mLayoutInflater = LayoutInflater.from(context);
        if (layoutResId != 0) {
            this.mLayoutResId = layoutResId;
        }
    }

    public BaseRecyclerAdapter(Context context, int layoutResId) {
        this(context, layoutResId, null);
    }

    public BaseRecyclerAdapter(Context context, int layoutResId, int minNumShowFooterView) {
        this(context, layoutResId, null);
        this.minNumShowFooterView = minNumShowFooterView;
    }

    /**
     * 添加头部xml
     *
     * @param header
     */
    public void addHeaderView(View header) {
        if (header == null) {
            throw new RuntimeException("header is null");
        }
        this.mHeaderView = header;
        this.notifyDataSetChanged();
    }

    /**
     * 添加尾部xml
     *
     * @param footer
     */
    public void addFooterView(View footer, boolean refresh) {
        if (refresh)
            mNextLoadEnable = false;
        if (footer == null) {
            throw new RuntimeException("footer is null");
        }
        this.mFooterView = footer;
        if (refresh)
            this.notifyDataSetChanged();
    }

    public void addFooterView(View footer) {
        addFooterView(footer, false);
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderView != null && position == 0) {
            return HEADER_VIEW;
        } else if (mEmptyView != null && getItemCount() == 1 && mEmptyEnable) {
            return EMPTY_VIEW;
        } else if (position == mData.size() + getHeaderViewsCount()) {
            if (mNextLoadEnable)
                return LOADING_VIEW;
            else
                return FOOTER_VIEW;
        }
        return getDefItemViewType(position);
    }

    /**
     * 这里可以自定义itemType
     *
     * @param position
     * @return
     */
    protected int getDefItemViewType(int position) {
        return super.getItemViewType(position);
    }


    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder;
        switch (viewType) {
            case LOADING_VIEW:
                baseViewHolder = getLoadingView(parent);
                break;
            case HEADER_VIEW:
                baseViewHolder = new BaseViewHolder(mContext, mHeaderView);
                break;
            case EMPTY_VIEW:
                baseViewHolder = new BaseViewHolder(mContext, mEmptyView);
                break;
            case FOOTER_VIEW:
//                baseViewHolder = new BaseViewHolder(mContext, mFooterView);
                baseViewHolder = getFooterView(parent);
                break;
            default:
                baseViewHolder = onCreateDefViewHolder(parent, viewType);
        }
        return baseViewHolder;

    }

    /**
     * 加载更多
     *
     * @param parent
     * @return
     */
    private BaseViewHolder getLoadingView(ViewGroup parent) {
        if (mLoadingView == null) {
            return createBaseViewHolder(parent, R.layout.item_loadmore_progress);
        }
        return new BaseViewHolder(mContext, mLoadingView);
    }

    /**
     * 加载更多
     *
     * @param parent
     * @return
     */
    private BaseViewHolder getFooterView(ViewGroup parent) {
        if (mFooterView == null) {
            mFooterView = createBaseViewHolder(parent, R.layout.item_loadmore_progress).getConvertView();
            TextView mFootTv = (TextView) mFooterView.findViewById(R.id.tv_foot);
            mFootTv.setText("已经到底了");
        }
        return new BaseViewHolder(mContext, mFooterView);
    }

    /**
     * 创建自定义布局 如果有多重类型的时候需要重写
     *
     * @param parent
     * @param viewType
     * @return
     */
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        return createBaseViewHolder(parent, mLayoutResId);
    }

    protected BaseViewHolder createBaseViewHolder(ViewGroup parent, int layoutResId) {
        return new BaseViewHolder(mContext, getItemView(layoutResId, parent));
    }

    protected View getItemView(int layoutResId, ViewGroup parent) {
        return mLayoutInflater.inflate(layoutResId, parent, false);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()) {
            case LOADING_VIEW:
                break;
            case HEADER_VIEW:
                break;
            case EMPTY_VIEW:
                break;
            case FOOTER_VIEW:
                break;
            default:
                convert((BaseViewHolder) holder, mData.get(holder.getLayoutPosition() - getHeaderViewsCount()));
                initItemClickListener(holder, (BaseViewHolder) holder);
                break;
        }
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
    }

    /**
     * 这是获取包括headerView +footerView总数 所以谨慎使用
     * @return
     */
    @Override
    public int getItemCount() {
        int count = mData.size() + getHeaderViewsCount() + getFooterViewsCount();
        mEmptyEnable = false;
        if (count == 0) {
            mEmptyEnable = true;
            count += getmEmptyViewCount();
        }
        return count;
    }

    public int getRealCount() {
        return mData.size();
    }

    /**
     * 初始化点击事件
     *
     * @param holder
     * @param baseViewHolder
     */
    private void initItemClickListener(final RecyclerView.ViewHolder holder, BaseViewHolder baseViewHolder) {
        if (onItemClickListener != null) {
            baseViewHolder.convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onItemClick(v, holder.getLayoutPosition() - getHeaderViewsCount());
                }
            });
        }
        if (onItemLongClickListener != null) {
            baseViewHolder.convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return onItemLongClickListener.onItemLongClick(v, holder.getLayoutPosition() - getHeaderViewsCount());
                }
            });
        }
    }


    public int getHeaderViewsCount() {
        return mHeaderView == null ? 0 : 1;
    }

    public int getFooterViewsCount() {
        if (mFooterView == null && !needDefaultFootView) {  //如果可以底部加载 则返回1
            return mNextLoadEnable ? 1 : 0;
        }
        if (!mNextLoadEnable && minNumShowFooterView > 0 && getRealCount() < minNumShowFooterView) {
            return 0;
        }
        return 1;

    }

    public int getmEmptyViewCount() {
        return mEmptyView == null ? 0 : 1;
    }

    public int getRealPosition(int position) {
        return position - getHeaderViewsCount();
    }


    public class OnRecyclerItemChildClickListener implements View.OnClickListener {
        public int position;

        @Override
        public void onClick(View v) {
            if (mChildClickListener != null)
                mChildClickListener.onItemChildClick(BaseRecyclerAdapter.this, v, getRealPosition(position));
        }
    }

    /**
     * 此方法回调itemViewHolder以及列表值
     *
     * @param helper
     * @param item
     */
    protected abstract void convert(BaseViewHolder helper, T item);


    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    /**
     * 子View点击事件
     *
     * @param childClickListener
     */
    public void setOnItemChildClickListener(OnItemChildClickListener childClickListener) {
        this.mChildClickListener = childClickListener;
    }

    /**
     * item click
     */
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public interface OnItemLongClickListener {
        boolean onItemLongClick(View view, int position);
    }

    public interface OnItemChildClickListener {
        void onItemChildClick(BaseRecyclerAdapter adapter, View view, int position);
    }

    public void setFullSpan(RecyclerView.ViewHolder holder) {
        if (holder.itemView.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {
            StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
            params.setFullSpan(true);
        }

    }

    public int[] getUnFullSpanType() {
        return new int[]{0};
    }

    //需要更换成footerView更换掉loadView
    private boolean needDefaultFootView;

    public void setNextLoadEnable(boolean enable) {
        if (this.mNextLoadEnable != enable) {
            this.mNextLoadEnable = enable;
            if (!enable && mFooterView == null) {
                needDefaultFootView = true;
            }
            notifyDataSetChanged();
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public T getItem(int position) {
        return mData.get(position);
    }

    public void remove(int position) {
        mData.remove(position);
        notifyItemRemoved(position);

    }

    public void add(int position, T item) {
        mData.add(position, item);
        notifyItemInserted(position);
    }

    /**
     * setting up a new instance to data;
     *
     * @param data
     */
    public void setNewData(List<T> data) {
        this.mData = data;
        notifyDataSetChanged();
    }

    /**
     * additional data;
     *
     * @param data
     */
    public void addData(List<T> data) {
        this.mData.addAll(data);
        notifyDataSetChanged();
//        notifyItemInserted(getItemCount() - 1);
    }

    /**
     * 设置显示footerView的item的个数限制 默认不限制
     *
     * @param minNumShowFooterView
     */
    public void setMinNumShowFooterView(int minNumShowFooterView) {
        this.minNumShowFooterView = minNumShowFooterView;
    }
}
